// source: 24 拼多多 20/12 taobao  13 jd   
// vaccineInfoId 19 22 31体检产品
import {
  throttle
} from '../../utils/util'
const app = getApp()
import api from '../../utils/api'
import {
  upload,
  imgUrl
} from '../../config/config'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    type: 2,
    fromData: [],
    radioValue: 0,
    totalForm: 0,
    vaccineOrder: {},
    vaccineOrderItemList: [],
    uploadImgList: [],
    codeNumber: '',
    isFullSucreen: false,
    showImageBox: false,
    sourceType: '',
    isRead: false,
    showMakesureBox: false,
    vaccineOrderItemParams: [],
    userMobile: '',
    optionsJson: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let userMobile = wx.getStorageSync('mobile')

    this.setData({
      isFullSucreen: app.globalData.isFullSucreen,
      userMobile: userMobile,
      optionsJson: options
    })
    this.getList(options)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  onUnload() {

  },

  formSubmit(e) {
    if (this.data.vaccineOrder.codeRequire) {
      if (!this.data.codeNumber && this.data.uploadImgList.length === 0) {
        wx.showToast({
          title: '请上传核销码',
          icon: 'error'
        })
        return
      }
    }

    let dataArray = this.data.fromData
    let vaccineOrderItemParams = []
    let canSubmit = true
    let phoneReg = /^0?1[3|4|5|6|7|8|9][0-9]\d{8}$/ // 手机号规则
    if (this.data.optionsJson.healthExam === 'true') {
      dataArray.forEach((item, index) => {
        let newJson = {}
        item.forEach((child, childIndex) => {
          newJson[child.key] = child.value
        })
        if (index * 1 === 0) {
          newJson.id = this.data.vaccineOrderItemList[0].id || ''
        } else {
          newJson.id = ''
        }
        if (!phoneReg.test(newJson.mobile)) {
          wx.showToast({
            title: '请输入正确手机号',
            icon: 'error'
          })
          canSubmit = false
        }
        newJson.areaId = 0
        newJson.areaName = ''
        vaccineOrderItemParams[index] = newJson
      })

    } else {
      if (!this.data.isRead) {
        wx.showToast({
          title: '请先阅读协议',
          icon: 'error'
        })
        canSubmit = false
        return
      }
      dataArray.forEach((item, index) => {
        let newJson = {}
        item.forEach((child, childIndex) => {
          newJson[child.key] = child.value
        })
        let idcardNo = newJson.idcardNo
        // 校验身份证
        if (newJson.type * 1 === 1) {
          let isCard = this.isIdNo(idcardNo)
          if (!isCard) {
            wx.showToast({
              title: '身份证号码有误',
              icon: 'error'
            })
            canSubmit = false
            return
          }

          let birthday = ''
          let sex = ''
          if (idcardNo.length == 15) {
            birthday = "19" + idcardNo.slice(6, 12);
            sex = idcardNo.charAt(14);
            if (sex % 2 == 0) {
              sex = 2;
            } else {
              sex = 1;
            }
          } else if (idcardNo.length == 18) {
            birthday = idcardNo.slice(6, 14);
            sex = idcardNo.charAt(16);
            if (sex % 2 == 0) {
              sex = 2;
            } else {
              sex = 1;
            }
          }
          birthday = birthday.replace(/(.{4})(.{2})/, "$1-$2-");
          newJson.birthday = birthday
          newJson.gender = sex

          for (let key in newJson) {
            if (!newJson[key]) {
              console.log(key)
              wx.showToast({
                title: '请完善预约人信息',
                icon: "error"
              })
              canSubmit = false
              break
            }
          }

        } else {
          newJson.other = newJson.idcardNo
          newJson.idcardNo = ''
          for (let key in newJson) {
            if (!newJson[key] && key !== 'idcardNo') {
              console.log(key, 'key============')
              wx.showToast({
                title: '请完善预约人信息',
                icon: "error"
              })
              canSubmit = false
              break
            }
          }
        }

        if (!phoneReg.test(newJson.mobile)) {
          wx.showToast({
            title: '请输入正确手机号',
            icon: 'error'
          })
          canSubmit = false
        }

        if (index * 1 === 0) {
          newJson.id = this.data.vaccineOrderItemList[0].id || ''
        } else {
          newJson.id = ''
        }

        if (newJson.relation * 1 === 5) {
          newJson.relation = 0
        } else {
          newJson.relation = newJson.relation * 1 + 1
        }

        let areaList = this.data.areaList[newJson.areaId * 1]
        newJson.areaId = areaList.id
        newJson.areaName = areaList.name
        vaccineOrderItemParams[index] = newJson
      })
    }

    if (!canSubmit) {
      return
    }
    console.log(vaccineOrderItemParams, 'vaccineOrderItemParams================')
    this.setData({
      showMakesureBox: true,
      vaccineOrderItemParams: vaccineOrderItemParams
    })
  },
  isIdNo(id) {
    // 身份证校验
    var num = id.toUpperCase();
    //身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X。
    if (!(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(num))) {
      //alert('输入的身份证号长度不对，或者号码不符合规定！\n15位号码应全为数字，18位号码末位可以为数字或X。');
      return false;
    }
    //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
    //下面分别分析出生日期和校验位
    var len, re;
    len = num.length;
    if (len == 15) {
      re = /^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/i;
      var arrSplit = num.match(re);

      //检查生日日期是否正确
      var dtmBirth = new Date('19' + arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4]);
      var bGoodDay;
      bGoodDay = (dtmBirth.getYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]));
      if (!bGoodDay) {
        //alert('输入的身份证号里出生日期不对！');
        return false;
      } else {
        //将15位身份证转成18位
        //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
        var arrInt = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        var arrCh = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
        var nTemp = 0,
          i;
        num = num.substr(0, 6) + '19' + num.substr(6, num.length - 6);
        for (i = 0; i < 17; i++) {
          nTemp += num.substr(i, 1) * arrInt[i];
        }
        num += arrCh[nTemp % 11];
        return true;
      }
    }
    if (len == 18) {
      re = /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/i;
      var arrSplit = num.match(re);

      //检查生日日期是否正确
      var dtmBirth = new Date(arrSplit[2] + "/" + arrSplit[3] + "/" + arrSplit[4]);
      var bGoodDay;
      bGoodDay = (dtmBirth.getFullYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]));
      if (!bGoodDay) {
        return false;
      } else {
        //检验18位身份证的校验码是否正确。
        //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
        var valnum;
        var arrInt = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        var arrCh = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
        var nTemp = 0,
          i;
        for (i = 0; i < 17; i++) {
          nTemp += num.substr(i, 1) * arrInt[i];
        }
        valnum = arrCh[nTemp % 11];
        if (valnum != num.substr(17, 1)) {
          return false;
        }
        return true;
      }
    }
    return false;
  },


  codeNumberInput(e) {
    let value = e.detail.value
    this.setData({
      codeNumber: value
    })
  },

  getList(option) {
    let {
      source,
      orderNo
    } = option

    api.orderDetail({
      data: {
        source,
        orderNo
      },
      success: res => {
        if (res.code * 1 === 0) {
          this.setData({
            vaccineOrder: res.data.vaccineOrder,
            vaccineOrderItemList: res.data.vaccineOrderItemList,
            sourceType: source * 1
          })
          this.searchArea(option)
          switch (res.data.vaccineOrder.status) {
            case -1:
              this.jumpSuccess(option)
              break;
            case 1:
              
              break;
            case 2:
              this.jumpSuccess(option)
              break;
            case 3:
              this.jumpSuccess(option)
              break;
            case 4:
              this.jumpSuccess(option)
              break;
          
            default:
              break;
          }
        }
      }
    })
  },

  searchArea(option) {
    let {
      source,
      orderNo
    } = option
    api.searchArea({
      data: {
        source: source,
        orderNo: orderNo
      },
      success: res => {
        if (res.code * 1 === 0) {
          this.setData({
            areaList: res.data.areaList
          }, () => {
            this.addPeople()
          })
        }

      }
    })
  },

  chooseImage() {
    const that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        console.log(res, 'aaaaaaaaaaa')
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths[0]
        wx.uploadFile({
          url: upload, //仅为示例，非真实的接口地址
          filePath: tempFilePaths,
          name: 'file',
          success(res) {
            console.log(res, 'res==================')
            const data = JSON.parse(res.data)
            if (data.code * 1 === 0) {
              let url = data.data.url
              that.setData({
                uploadImgList: [...that.data.uploadImgList, url]
              })
            }
            //do something
          },
          fail(err) {
            console.log(err)
          }
        })
      },
      fail(err) {
        console.log(err)
      }
    })
  },

  radioChange(e) {
    let value = e.detail.value * 1
    this.setData({
      radioValue: value
    })
  },

  remove() {
    let data = this.data.fromData
    data.splice(this.data.totalForm, 1)
    this.setData({
      fromData: data,
      totalForm: this.data.totalForm - 1
    })
  },

  removePeople(e) {
    if (this.data.totalForm * 1 <= 1) {
      return
    }
    this.showModal({
      title: '删除预约人',
      content: '确认删除联系人',
      confirmFun: this.remove
    })
  },

  addPeople(num = 1) {

    if (this.data.vaccineOrder.source !== 24 && this.data.totalForm * 1 >= this.data.vaccineOrder.quantity * 1) {
      return
    }


    let areaList = []
    this.data.areaList.forEach(item => {
      areaList.push(item.name)
    })

    let vaccineOrderItemList = {}
    if (this.data.totalForm * 1 === 0) {
      vaccineOrderItemList = this.data.vaccineOrderItemList
    } else {
      vaccineOrderItemList = {
        name: '',
        type: '',
        idcardNo: '',
        gender: '',
        birthday: '',
        mobile: '',
        relation: '',
        areaId: '',
        address: ''
      }
    }

    let formKey = []
    if (this.data.optionsJson.healthExam === 'true') {
      formKey = [{
          type: 'input',
          label: '姓名',
          value: vaccineOrderItemList.name,
          required: true,
          key: 'name'
        },
        {
          type: 'input',
          label: '联系电话',
          value: vaccineOrderItemList.mobile,
          required: true,
          key: 'mobile'
        }
      ]
    } else {
      formKey = [{
          type: 'input',
          label: '姓名',
          value: vaccineOrderItemList.name || '',
          required: true,
          key: 'name'
        },
        {
          type: 'radio',
          label: '证件',
          value: vaccineOrderItemList.type || '1',
          required: true,
          key: 'type',
          radioGroup: [{
              label: '身份证',
              value: '1',
              checked: true
            },
            {
              label: '其他',
              value: '2'
            }
          ]
        },
        {
          type: 'input',
          label: '证件号',
          key: 'idcardNo',
          value: vaccineOrderItemList.idcardNo || '',
          required: true
        },
        {
          type: 'radio',
          label: '性别',
          value: '2',
          key: 'gender',
          required: true,
          hidden: true,
          radioGroup: [{
              label: '男',
              value: '1',
              checked: false
            },
            {
              label: '女',
              value: '2',
              checked: true
            },
            {
              label: '未知',
              value: '0',
              checked: false
            }
          ]
        },
        {
          type: 'date',
          label: '生日',
          hidden: true,
          value: vaccineOrderItemList.birthday || '',
          key: 'birthday',
          required: true,
          showLabel: ''
        },
        {
          type: 'input',
          label: '联系电话',
          value: vaccineOrderItemList.mobile || '',
          required: true,
          key: 'mobile'
        },
        {
          type: 'selector',
          label: '与本人关系',
          value: vaccineOrderItemList.relation || '0',
          required: true,
          key: 'relation',
          array: [
            '本人',
            '父母',
            '子女',
            '夫妻',
            '亲属',
            '其他'
          ],
          showLabel: ''
        },
        {
          type: 'selector',
          label: '适用城市',
          value: vaccineOrderItemList.areaId || '',
          required: true,
          key: 'areaId',
          array: areaList,
          showLabel: ''
        },
        {
          type: 'input',
          label: '现居地址',
          value: vaccineOrderItemList.address || '',
          required: true,
          key: 'address'
        }
      ]
    }

    let fromData = this.data.fromData
    let totalForm = this.data.totalForm

    fromData[this.data.totalForm] = formKey

    this.setData({
      fromData: fromData,
      totalForm: totalForm + 1
    })

  },

  remove_Image(e) {
    let index = e.currentTarget.dataset.index * 1
    let uploadImgList = this.data.uploadImgList
    uploadImgList.splice(index, 1)
    this.setData({
      uploadImgList: uploadImgList
    })
  },

  showModal({
    title = '提示',
    content = '这是一个模态弹窗',
    confirmFun = console.log('confirmFun')
  }) {
    wx.showModal({
      title: title,
      content: content,
      success(res) {
        if (res.confirm) {
          confirmFun()
        }
      }
    })
  },

  showImage() {
    this.setData({
      showImageBox: true
    })
  },

  closeMask() {
    this.setData({
      showImageBox: false
    })
  },

  toForm(value) {
    let data = value.detail
    data.forEach((item, index) => {
      item.forEach(child => {
        if (child.key === 'type') {
          if (child.value === '1') {
            this.showCardTrue(index, data)
          } else {
            this.showCardWrong(index, data)
          }
        }
      })
    })
  },
  showCardTrue(index, data) {
    data[index].forEach(item => {
      if (item.key === "birthday") {
        item.hidden = true
      }
      if (item.key === "gender") {
        item.hidden = true
      }
    })
    this.setData({
      fromData: data
    })
  },
  showCardWrong(index, data) {
    data[index].forEach(item => {
      if (item.key === "birthday") {
        item.hidden = false
      }
      if (item.key === "gender") {
        item.hidden = false
      }
    })
    this.setData({
      fromData: data
    })
  },
  moveToAgree(e) {
    throttle(function (e) {
      wx.navigateTo({
        url: '../agreement/agreement?type=1'
      })
    }, 2000)
  },

  readChange() {
    this.setData({
      isRead: !this.data.isRead
    })
  },
  stop() {
    return
  },
  cancelMakesureBox() {
    this.setData({
      showMakesureBox: false
    })
  },

  makesureForm() {
    const {
      optionsJson,
      vaccineOrder,
      uploadImgList,
      codeNumber,
      vaccineOrderItemParams
    } = this.data
    let submitData = {
      vaccineOrderId: vaccineOrder.vaccineOrderId, //订单号
      codeNumber: codeNumber, //核销码
      codeUrl: uploadImgList.join(',') || '', //核销码图片
      vaccineOrderItemParams: vaccineOrderItemParams
    }
    api.orderBook({
      data: submitData,
      success: (res) => {
        if (res.code * 1 === 0) {
          wx.showToast({
            title: '登记完成',
            icon: 'success'
          })
          this.jumpSuccess(optionsJson)
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'error'
          })
        }
      }
    })
  },
  jumpSuccess(optionsJson) {
    wx.redirectTo({
      url: `/pages/registered-success/index?source=${optionsJson.source}&orderNo=${optionsJson.orderNo}`
    })
  },

})